<template>
	<view>
		<uni-list class="weld-outline">
		  <uni-list-item
		   :title="'焊接编号' + weld.F_WeldNum"
		   :note="weld.F_WeldTime"
			 :rightText="weld.totalResult"
			 :rightColor="weld.finalColor"
		   :thumb="weld.hotImage"/>
		</uni-list>
		<divider></divider>
		<view class="content-bottom">
			<section-title lineColor="#DC2115" title="照片上传"></section-title>
			<view class="photo-box">
				<view class="photo-item">
					<image class="photo" v-if="photoList[0].src" :src="photoList[0].src" mode="aspectFill" @click="previewImage(0)"></image>
					<view class="photo no-photo" v-else @click="chooseImage(0)">
						<image class="empty-photo" src="/static/image/common/weld/nophoto.png"></image>
					</view>
					<view class="photo-title">操作焊工照片</view>
					<view class="close-image" @click="removePhoto(0)">
						<image src="/static/image/common/weld/close.png"></image>
					</view>
				</view>
				<view class="photo-item">
					<image class="photo" v-if="photoList[1].src" :src="photoList[1].src" mode="aspectFill" @click="previewImage(1)"></image>
					<view class="photo no-photo" v-else @click="chooseImage(1)">
						<image class="empty-photo" src="/static/image/common/weld/nophoto.png"></image>
					</view>
					<view class="photo-title">管件信息照片</view>
					<view class="close-image" @click="removePhoto(1)">
						<image src="/static/image/common/weld/close.png"></image>
					</view>
				</view>
				<view class="photo-item">
					<image class="photo" v-if="photoList[2].src" :src="photoList[2].src" mode="aspectFill" @click="previewImage(2)"></image>
					<view class="photo no-photo" v-else @click="chooseImage(2)">
						<image class="empty-photo" src="/static/image/common/weld/nophoto.png"></image>
					</view>
					<view class="photo-title">氧化皮去除照片</view>
					<view class="close-image" @click="removePhoto(2)">
						<image src="/static/image/common/weld/close.png"></image>
					</view>
				</view>
				<view class="photo-item">
					<image class="photo" v-if="photoList[3].src" :src="photoList[3].src" mode="aspectFill" @click="previewImage(3)"></image>
					<view class="photo no-photo" v-else @click="chooseImage(3)">
						<image class="empty-photo" src="/static/image/common/weld/nophoto.png"></image>
					</view>
					<view class="photo-title">管材装夹照片</view>
					<view class="close-image" @click="removePhoto(3)">
						<image src="/static/image/common/weld/close.png"></image>
					</view>
				</view>
				<view class="photo-item">
					<image class="photo" v-if="photoList[4].src" :src="photoList[4].src" mode="aspectFill" @click="previewImage(4)"></image>
					<view class="photo no-photo" v-else @click="chooseImage(4)">
						<image class="empty-photo" src="/static/image/common/weld/nophoto.png"></image>
					</view>
					<view class="photo-title">焊接完成照片</view>
					<view class="close-image" @click="removePhoto(4)">
						<image src="/static/image/common/weld/close.png"></image>
					</view>
				</view>
				<view class="photo-item">
				</view>
			</view>
		</view>
		<divider v-if="ifSupervisor"></divider>
		<view class="content-middle" v-if="ifSupervisor">
			<section-title lineColor="#DC2115" title="修改状态"></section-title>
			<view class="middle-item">
				<view class="item-title">将项目状态修改为</view>
				<radio-button :items="radioItem" @change="selectItem" :currentIndex="radioButtonIndex"></radio-button>
			</view>
			<view class="middle-item" v-if="!appearance.ifPass">
				<view class="item-title">选择理由</view>
				<picker @change="changePicker" :value="pickerIndex" :range="pickerArray" range-key="name">
					<view class="uni-input" :class="pickerIndex === 0 ? 'first-input': ''">{{pickerArray[pickerIndex].name}}</view>
				</picker>
			</view>
		</view>
		<button class="submit-button" type="primary" @click="updateInfo">提交</button>
		<modal v-model="showModalForRemovePhoto" confirm-style="color: #DC2115" title='询问'
					 text='确定要删除该照片吗？' @confirm='doRemovePhoto'></modal>
		<modal v-model="showModalForUpdateInfo" confirm-style="color: #DC2115" title='询问'
					 text='确定更新本条热熔记录信息？' @confirm='doUpdateInfo'></modal>
		<message ref="message"></message>
	</view>
</template>

<script>

	import uniList from '@/components/uni/uni-list.vue'
	import uniListItem from '@/components/uni/uni-list-item.vue'
	import divider from "../../components/divider";
	import sectionTitle from "../../components/section-title"
	import radioButton from "@/components/radio-button.vue"

	import {edit} from "../../api/hot/edit";
	import {getTodayDate} from "../../js/common";
	import {config} from "../../config";

  import store from "@/store/index.js"

	export default {
		data() {
			return {
				weld: {},
				radioItem: [{
					name: '合格',
					value: 1
				}, {
					name: '不合格',
					value: 0
				}],
				appearance: {
					ifPass: true
				},
				userRole: uni.getStorageSync('role'),
				photoList: [{src: ''}, {src: ''}, {src: ''}, {src: ''}, {src: ''}],
				pickerIndex: 0,
				pickerArray: [{
					"name": "请选择",
					"value": "-1",
					"index": 0
				}, {
					"name": "不合格",
					"value": "0",
					"index": 1
				}, {
					"name": "不合格（翻边小）",
					"value": "2",
					"index": 2
				}, {
					"name": "不合格（翻边大）",
					"value": "3",
					"index": 3
				}, {
					"name": "不合格（翻边有气孔）",
					"value": "4",
					"index": 4
				}, {
					"name": "不合格（其它）",
					"value": "5",
					"index": 5
				}],
				showModalForRemovePhoto: false,
				showModalForUpdateInfo: false,
				// 待删除的图片索引
				toDeleteImageIndex: Number,
        // 在updateInfo和doUpdateInfo方法中之间需要传递appearanceId的值，所以在这里放一个副本
        tmpAppearance: ''
			}
		},
    computed: {
		  /**
       * 判断是否为监理
       */
		  ifSupervisor() {
		  	// TODO 模拟每个用户都是监管
				return this.userRole === "100002" || this.userRole === "100055"
        // return true
      },
			/**
			 * ifPass为true，说明外观合格，那么index为0，指向的是{name: '合格', value: 1}
			 * 反之index为1，指向的是{name: '不合格', value: 0}
			 */
			radioButtonIndex() {
				return this.appearance.ifPass ? 0 : 1
			}
    },
		onLoad(options) {
			this.weld = JSON.parse(decodeURIComponent(options.weld));
			// 给photoList赋值
			this.photoList = this.weld.F_ImageUrl.split(';').map(item => {
				return {src: item}
			});
			// 给ifPass赋值
			let ifPass;
			if (this.weld.F_ApperenceCode !== null) {
				if (this.weld.F_ApperenceCode === '' || this.weld.F_ApperenceCode === null) {
					ifPass = true
				} else {
					ifPass = this.weld.F_ApperenceCode === "1";
				}
				this.$set(this.appearance, 'ifPass', ifPass);
			}
			// 不合格的话需要给pickerIndex赋值
			if (!ifPass) {
				let item = this.pickerArray.filter(item => this.weld.F_Apperence === item.name);
				this.$set(this, 'pickerIndex', parseInt(item[0].index));
			}
		},
		components: {
			uniList, uniListItem, divider, sectionTitle, radioButton
		},
		onReady() {
		  this.$refs.message.setMessageToStore(this.$refs.message)
    },
		methods: {
			selectItem(value, index) {
				// this.appearance.ifPass = parseInt(value);
				this.$set(this.appearance, 'ifPass', index === 0)
			},
			/**
			 * 打开移除照片的弹窗
			 * @param index 移除照片的索引值
			 */
			removePhoto(index) {
				this.showModalForRemovePhoto = true;
				this.toDeleteImageIndex = index;
			},
			/**
			 * 移除照片
			 */
			doRemovePhoto() {
				this.photoList.splice(this.toDeleteImageIndex, 1, {src: ''});
				console.log(this.toDeleteImageIndex);
				console.log(this.photoList);
			},
			changePicker(e) {
				this.pickerIndex = parseInt(e.detail.value);
			},
			/**
			 * 为index所在的框选择照片
			 * @param index 照片框的索引
			 */
			chooseImage(index) {
				uni.chooseImage({
					sizeType: ['compressed'],
					sourceType: ['camera'],
					success: res1 => {

						uni.showLoading({
              title: '上传图片中，请稍后',
              mask: true
            })
						// 成功后立即上传
            uni.uploadFile({
              url: config.UPLOAD_BASE_URL + '/upload',
              filePath: res1.tempFilePaths[0],
              name: 'file',
              success: res => {
                let data = JSON.parse(res.data);
                let imgUrl = config.UPLOAD_BASE_URL + data.data;
                if (data.code === 200) {
                  this.$refs.message.success('上传成功');
                  this.photoList.splice(index, 1, {src: imgUrl});
                } else {
                  this.$refs.message.error(data.message);
                }
              },
              fail: err => {
                console.log(err);
                this.$refs.message.error("网络错误，请稍后再试");
              },
              complete: () => {
                uni.hideLoading();
              }
            });
					}
				});
			},
			/**
			 * 从index所在的框浏览图片
			 * @param index 照片框的索引
			 */
			previewImage(index) {
				uni.previewImage({
					urls: this.photoList.filter(item => item.src).map(item => item.src),
				})
			},
			/**
			 * 显示是否更新热熔记录的弹窗
			 */
			updateInfo() {
				let appearanceId;
				// 如果外观合格，那么appearanceId就是1
				if (this.appearance.ifPass) {
					appearanceId = "1";
				} else {
					// 如果不合格，那么要到pickerArray数组中确定是哪种不合格
					appearanceId = this.pickerArray[this.pickerIndex].value
				}
				if (appearanceId === "-1") {
					this.$refs.message.error("请选择不合格的原因");
					return;
				}
				this.tmpAppearance = appearanceId;
				this.showModalForUpdateInfo = true;
			},
			/**
			 * 更新热熔记录
			 */
			doUpdateInfo() {
				let data = {
					F_RecordId: this.weld.F_RecordId,
					F_Longitude: this.weld.F_Longitude,
					F_Latitude: this.weld.F_Latitude,
					F_imageUrl: this.photoList.map(item => item.src).join(";"),
					F_ApperenceCode: this.tmpAppearance
				}
				edit(data).then(res => {
					if (res.data.code === 200) {
						this.$refs.message.success('更新成功');
						// 后台提供的接口会在不传时间条件，和传所有的时间条navigateTo件的结果会不一样，所以为了提升体验，就在跳转前手动设置时间条件
						let query = {};
						query.StartTime = '1970-01-01'
						query.EndTime = getTodayDate();
						setTimeout(() => {
              uni.redirectTo({
                url: '/pages/hot/list?query=' + encodeURIComponent(JSON.stringify(query))
              })
            }, 500)
					} else {
						this.$refs.message.error(res.data.info);
					}
				})
			}
		},
    /**
     * 点击右上角首页按钮，跳转到首页
     */
    onNavigationBarButtonTap() {
      store.commit('returnToHome')
    }
	}
</script>

<style>
	page {
		background-color: #f5f5f5;
	}
</style>

<style scoped lang="scss">
	@import "~@/static/css/weld/edit.scss"
</style>
